import styles from './styles.less';
import {Input, message} from 'antd';
import {connect, useSearchParams} from 'umi';
import {useState, useEffect} from 'react';

const App = props => {

  const {dispatch, loading} = props;
  const [username, setUsername] = useState(undefined);
  const [password, setPassword] = useState(undefined);
  const [searchParams] = useSearchParams();

  useEffect(() => {
    const keyDownHandler = event => {
      if (event.key === 'Enter') {
        onSubmit(event);
      }
    };

    document.addEventListener('keydown', keyDownHandler);
    return () => {
      document.removeEventListener('keydown', keyDownHandler);
    };
  }, [username, password]);

  /* 登录表单提交 */
  const onSubmit = e => {
    e.preventDefault();
    if (loading) {
      return false;
    }

    if (!username || !username.trim()) {
      message.error('登录账号不能为空');
      return;
    }
    if (!password || !password.trim()) {
      message.error('登录密码不能为空');
      return;
    }

    message.loading('正在提交...', 0);
    // 执行登陆请求
    dispatch({
      type: 'PLogin/token',
      payload: {username, password},
      callback: () => {
        setTimeout(() => {
          if (searchParams.get('redirect')) {
            window.location.href = searchParams.get('redirect');
          } else {
            window.location.href = '/';
          }
        }, 1500);
      },
    });
  };

  return (
    <div className={styles.container}>
      <div className={styles.center}>
        <div className={styles.form}>
          <div className={styles.row}>
            <img src={'/image/login/username.png'} alt={''}/>
            <Input placeholder={'请输入登录账号'} onChange={e => setUsername(e.target.value)}/>
          </div>
          <div className={styles.row}>
            <img src={'/image/login/password.png'} alt={''}/>
            <Input type={'password'} placeholder={'请输入登录密码'} onChange={e => setPassword(e.target.value)}/>
          </div>
          <div className={styles.login}>
            <div onClick={onSubmit}>登录</div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default connect(({loading}) => ({
  loading: loading.effects['PLogin/token'],
}))(App);
